import React, { useEffect } from 'react';
import AMapLoader from '@amap/amap-jsapi-loader';

window._AMapSecurityConfig = {
    securityJsCode: "e8cb186db8ce345f8f09f4253d6e8d1e",
};

const AMapExample = (props) => {
    let originName = props.originName
    let destinationName = props.destinationName
    useEffect(() => {
        // 浏览器获取当前位置
        navigator.geolocation.getCurrentPosition((position) => {
            AMapLoader.load({
                "key": "93ac23764b679a2cfd4c8887ab99e648 ",   // 申请好的Web端开发者Key，首次调用 load 时必填
                "version": "2.0",   // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                "plugins": ['AMap.Driving']  // 加载路径规划插件
            }).then((AMap) => {
                let amap = new AMap.Map('mapContainer', { // mapcontainer为容器的id
                    zoom: 15, //初始化地图层级
                    center: [position.coords.longitude, position.coords.latitude] //初始化地图中心点
                });

                // 设置起点和终点
                var points = [
                    { keyword: originName, city: "北京" },
                    { keyword: destinationName, city: "北京" },
                ];

                // 创建Driving实例
                const driving = new AMap.Driving({
                    map: amap,
                    panel: "panel" // 导航结果展示面板的id
                });

                // 使用Driving实例进行路径规划
                driving.search(points, (status, result) => {
                    if (status === 'complete') {
                        console.log(result);
                        console.log('绘制驾车路线完成');
                    } else {
                        console.error('获取驾车数据失败:', result);
                    }
                });

            }).catch(e => {
                console.log(e);
            })
        });

    }, []);

    return (
        <>
            <div id="mapContainer" style={{ width: '100%', height: '400px' }}></div>
            <div id="panel" style={{ width: '100%', minHeight: '200px' }}></div>
        </>
    );
};

export default AMapExample;